package cn.j2e.security;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cpms.dto.LoginUser;

import cn.j2web.core.utils.EncodeDkogUtils;

public class CookieUtils {
	
	private static String COOKIE_LOGIN_USERNAME="SESSION_LOGIN_USERNAME";
	
	private static String COOKIE_LOGIN_PASSWORD="SESSION_LOGIN_PASSWORD";
	
	/**
	 * 把用户名和密码写入cookie中
	 * @param request
	 * @param response
	 * @param loginUser
	 * @param isSavePasswordToCookie， 判断是否写入cookie
	 */
	public static void write(HttpServletRequest request,HttpServletResponse response,String username,String password,boolean isSavePasswordToCookie){
        String host = request.getServerName();
        Cookie cookie = new Cookie(COOKIE_LOGIN_USERNAME, username); // 保存用户名到Cookie
        cookie.setPath("/");
        cookie.setDomain(host);
        response.addCookie(cookie);
        if (isSavePasswordToCookie) {
          // 保存密码到Cookie，注意需要加密一下
          cookie = new Cookie(COOKIE_LOGIN_PASSWORD, EncodeDkogUtils.encodeByMD5(password));
          cookie.setPath("/");
          cookie.setDomain(host);
          response.addCookie(cookie);
        }
	}
	
	/**
	 * 从 cookie 取得用户名和密码
	 * @param request
	 * @param response
	 * @param loginUser
	 * @param isSavePasswordToCookie
	 * @return
	 */
	public static LoginUser read(HttpServletRequest request,
			HttpServletResponse response,
			boolean isSavePasswordToCookie) {
		Cookie[] cookies = request.getCookies();
		LoginUser lud = new LoginUser();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (COOKIE_LOGIN_USERNAME.equals(cookie.getName())) {
					lud.setUserName(cookie.getValue());
				}
				if (COOKIE_LOGIN_PASSWORD.equals(cookie.getName())) {
					lud.setPassWord(cookie.getValue());
				}
			}
		}
		return lud;
	}
}
